package edu.stthomas.seis752.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import edu.stthomas.seis752.model.Media;
import edu.stthomas.seis752.model.User;
import edu.stthomas.seis752.service.MediaService;
import edu.stthomas.seis752.service.UserService;



@Controller
public class MediaController {


	@Autowired
	private MediaService mediaService;

	@Autowired
	private UserService userService;

	private static final Logger logger = LoggerFactory.getLogger(MediaController.class);

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(@RequestParam("files[]") ArrayList<MultipartFile> files,
	                 @RequestParam("title") String mediaName, 
	                 Model model) throws IllegalStateException, IOException {
		List<Media> mediaList = new ArrayList<Media>();
        // obtain authenticated user
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        User owner = userService.getUserByUserName(name);
		if (files != null && files.size() > 0) {
			for (MultipartFile multipartFile : files) {
			    Media media = mediaService.uploadMedia(multipartFile, owner, mediaName);
			    // when media uploaded correctly
			    if(media != null){
			       mediaList.add(media);
			    }
			}
			// send the list to model
			model.addAttribute("mediaList", mediaList);
		}
		return "listMedia";
	}
}
